import 'dart:math';

import 'package:sleep/help_style.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';

class FaDetailChart extends StatelessWidget {
  final List<FlSpot>? spots;

  final double aspectRatio;
  final double? maxX;
  final double? minX;
  final double? maxY;
  final double? minY;
  final double mimResolution;

  FaDetailChart(
      {Key? key,
      this.spots,
      required this.aspectRatio,
      this.maxX,
      this.minX,
      this.maxY,
      required this.mimResolution,
      this.minY})
      : super(key: key);

  List<Color> gradientColors = [
    Colors.green,
    Colors.green,
  ];

  final mainGridLineColor = Colors.blue;
  @override
  Widget build(BuildContext context) {
    return AspectRatio(
      aspectRatio: aspectRatio,
      child: LineChart(
        mainData(),
        swapAnimationDuration: const Duration(milliseconds: 0),
      ),
    );
  }

  LineChartData mainData() {
    List<FlSpot>? sp = spots;
    if (maxY != null && minY != null) {
      sp = spots
          ?.map((sport) => FlSpot(sport.x, max(min(sport.y, maxY!), minY!)))
          .toList();
    }

    return LineChartData(
      gridData: FlGridData(
        show: true,
        drawVerticalLine: true,
        horizontalInterval: mimResolution,
      ),
      titlesData: FlTitlesData(
        show: true,
        rightTitles: AxisTitles(
          sideTitles: SideTitles(showTitles: false),
        ),
        topTitles: AxisTitles(
          sideTitles: SideTitles(showTitles: false),
        ),
        bottomTitles: AxisTitles(
          sideTitles: SideTitles(
            showTitles: true,
            reservedSize: 10,
          ),
        ),
        leftTitles: AxisTitles(
          sideTitles: SideTitles(
              showTitles: true,
              interval: mimResolution,
              reservedSize: 20,
              getTitlesWidget: leftTitleWidgets),
        ),
      ),
      borderData: FlBorderData(
        show: true,
        border: Border.all(color: const Color(0xff37434d)),
      ),
      minX: minX,
      maxX: maxX,
      minY: minY,
      maxY: maxY,
      lineBarsData: [
        if (spots != null && spots!.isNotEmpty)
          LineChartBarData(
            spots: sp,
            isCurved: true,
            color: HelpStyle.primarycolor,
            barWidth: 1.5,
            isStrokeCapRound: true,
            dotData: FlDotData(
              show: false,
            ),
          ),
      ],
    );
  }

  Widget leftTitleWidgets(double value, TitleMeta meta) {
    TextStyle style = HelpStyle.smallStyle.copyWith(fontSize: 10);
    String text;
    text = value.toStringAsFixed(1);
    final v = ((value * 100000000000).ceil() / 100000000000);
    if (v == 0) {
      text = text = 0.toStringAsFixed(1);
    }
    return Text(text, style: style, textAlign: TextAlign.center);
  }
}
